<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="出生年月" prop="birthday">
        <el-date-picker clearable
          v-model="queryParams.birthday"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出生年月">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="电话" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:user:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:user:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:user:del']"
        >批量删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="userList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column label="用户性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span>{{ scope.row.sex === 0 ? '男' : (scope.row.sex === 1 ? '女' : '暂无') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="生日" align="center" prop="birthday" />

      <el-table-column label="总消费次数" align="center" prop="consumeCount" />

      <el-table-column label="消费频次" align="center" prop="consumeCountType">
        <template slot-scope="scope">
          <span v-if="scope.row.consumeCount < 3">低频</span>
          <span v-if="scope.row.consumeCount > 2 && scope.row.consumeCount < 7">低频</span>
          <span v-if="scope.row.consumeCount > 6"> 高频</span>
        </template>
      </el-table-column>



      <el-table-column label="是否会员" align="center" prop="isMember">
        <template slot-scope="scope">
          <span>{{ scope.row.isMember == 0 ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="储蓄卡" align="center" prop="isSaveCardStr">
        <template slot-scope="scope">
          <span>{{ scope.row.isSaveCardStr == 0 ? '暂无' : '有' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券" align="center" prop="isCouponStr">
        <template slot-scope="scope">
          <span>{{ scope.row.isCouponStr ? scope.row.isCouponStr : '暂无' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!-- <el-table-column label="创建人" align="center" prop="createBy" /> -->

      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="修改人" align="center" prop="updateBy" />

      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleGive(scope.row)"
            v-hasPermi="['business:user:give']"
          >赠送优惠券</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['business:user:give']">查看优惠券</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:user:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleblacklist(scope.row)"
            v-hasPermi="['business:user:black']">黑名单</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:user:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户姓名" style="width: 222px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话" style="width: 222px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select clearable v-model="form.sex">
                <el-option v-for="(item, index) of List" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="form.birthday" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 赠送优惠券弹框 -->
    <el-dialog :title="title" :visible.sync="giveDialog" width="1200px" append-to-body :close-on-click-modal='false'>
      <el-table v-loading="loading" :data="storeList" @selection-change="handleGiveChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="序号" align="center" prop="storeName" /> -->
        <el-table-column label="优惠券名称" align="center" prop="name" width="120" />
        <el-table-column label="优惠券类型" align="center" prop="couponTypeName" width="120" />
        <el-table-column label="所属区域" align="center" prop="regionName" width="120">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{ scope.row.regionName === null ? '无' : scope.row.regionName }}
              </div>
              <p class="descStyle">{{ scope.row.regionName === null ? '无' : scope.row.regionName }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="所属门店" align="center" prop="storeName">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{ scope.row.storeName === null ? '无' : scope.row.storeName }}
              </div>
              <p class="descStyle">{{ scope.row.storeName === null ? '无' : scope.row.storeName }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="优惠券图片" align="center" prop="picture" width="160">
          <template slot-scope="scope">
            <image-preview :src="scope.row.picture" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="优惠门槛" align="center" prop="fullAmount" width="120" />
        <el-table-column label="优惠金额" align="center" prop="discountAmount" width="120" />
        <!-- <el-table-column label="适用项目" align="center" prop="projectName"  width="120"/> -->
        <el-table-column label="适用项目" align="center" prop="projectName">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{ scope.row.projectName === null ? '无' : scope.row.projectName }}
              </div>
              <p class="descStyle">{{ scope.row.projectName === null ? '无' : scope.row.projectName }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用周期" align="center" prop="useToday" width="120" />
        <el-table-column label="上架" align="center" prop="state" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.state == "1" ? "上架" : "下架" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      </el-table>
      <pagination v-show="total1 > 0" :total="total1" :page.sync="pageNum" :limit.sync="pageSize"
        @pagination="getStoreList" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chargeBackSubmit">确 定</el-button>
        <el-button @click="chargeBackCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看优惠券" :visible.sync="ViewDialog" width="1200px" append-to-body
      :close-on-click-modal='false'>
      <el-table :data="viewList">
        <!-- @selection-change="handleGiveChange" -->
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" prop="storeName" />
        <el-table-column label="优惠券名称" align="center" prop="name" width="120" />
        <el-table-column label="优惠券类型" align="center" prop="couponTypeName" width="120" />
        <el-table-column label="所属区域" align="center" prop="regionName" width="120">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px"></div>
              <div>{{ scope.row.regionName === null ? '无' : scope.row.regionName }}</div>
              <p class="descStyle">{{ scope.row.regionName === null ? '无' : scope.row.regionName }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="primary" @click="delet(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chargeBackSubmit">确 定</el-button>
        <el-button @click="chargeBackCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, listblacklist, giveUserCoupon } from "@/api/system/users";
import { listcoupon } from "@/api/system/coupon/couponList";
export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1: null,
      pageNum: 1,
      pageSize: 10,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 查看优惠券
      ViewDialog: false,
      viewList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        sex: null,
        birthday: null,
        phoneNumber: null,
        openId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          // { min: 1, max: 10, message: '长度在 1到 10 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
      },
      List: [
        {
          key: 0,
          value: '男'
        },
        {
          key: 1,
          value: '女'
        },
      ],
      // 优惠券表格数据
      storeList: [],
      //优惠券弹框
      giveDialog: false,
      id: null,
      userId: null
    };
  },
  created() {
    // this.getList();
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询优惠券列表 */
    getStoreList() {
      this.loading = true;
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      listcoupon(params).then((response) => {
        this.storeList = response.rows;
        this.total1 = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getStoreList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getStoreList()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userName: null,
        sex: null,
        birthday: null,
        phoneNumber: null,
        openId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //赠送优惠券多选框选中数据
    handleGiveChange(selection) {
      this.couponIds = selection.map((item) => item.id);
      this.couponIds = this.couponIds.join(',')
      console.log(this.couponIds, 'this.couponIds')
    },
    //赠送优惠券按钮操作
    handleGive(row) {
      this.giveDialog = true
      this.title = "优惠券列表";
      this.id = row.id
      this.userId = row.userId
      this.getStoreList()
    },
    //赠送优惠券提交
    chargeBackSubmit() {
      const params = {
        userId: this.userId,
        couponIds: this.couponIds
      }
      giveUserCoupon(params).then(response => {
        if (response.code == 200) {
          this.giveDialog = false;
          this.$message.success(response.msg)
        }
      });
    },
    //赠送优惠券取消
    chargeBackCancel() {
      this.giveDialog = false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.ViewDialog = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleblacklist(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认把用户为"' + row.userName + '"的数据项列入黑名单？').then(function () {
        return listblacklist({ id: ids });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("确认成功");
      }).catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户为"' + row.userName + '"的数据项？').then(function () {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.dialog-footer {
  text-align: center;
}

.descStyle {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tooltip {
  max-width: 650px;
}
</style>